package com.example.auth.demo.controller;

import com.example.auth.demo.domain.PageResult;
import com.example.auth.demo.domain.ResultCode;
import com.example.auth.demo.domain.ResultJson;
import com.example.auth.demo.domain.auth.Role;
import com.example.auth.demo.domain.auth.ResponseUserToken;
import com.example.auth.demo.domain.auth.User;
import com.example.auth.demo.domain.auth.UserDetail;
import com.example.auth.demo.service.AuthService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import com.example.auth.demo.domain.auth.Equipment;
import com.example.auth.demo.domain.auth.Task;

import com.example.auth.demo.domain.auth.Player;
import com.example.auth.demo.domain.auth.PlayerFeedback;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;



@RestController
@Api(description = "登陆注册及刷新token")
@RequestMapping("/api/v1")
public class AuthController {
    @Value("${jwt.header}")
    private String tokenHeader;

    private final AuthService authService;

    @Autowired
    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping(value = "/login")
    @ApiOperation(value = "登陆", notes = "登陆成功返回token,登陆之前请先注册账号")
    public ResultJson<ResponseUserToken> login(
            @Valid @RequestBody User user){
        final ResponseUserToken response = authService.login(user.getName(), user.getPassword());
        return ResultJson.ok(response);
    }

    @GetMapping(value = "/logout")
    @ApiOperation(value = "登出", notes = "退出登陆")
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")})
    public ResultJson logout(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            return ResultJson.failure(ResultCode.UNAUTHORIZED);
        }
        authService.logout(token);
        return ResultJson.ok();
    }

    @GetMapping(value = "/user")
    @ApiOperation(value = "根据token获取用户信息", notes = "根据token获取用户信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "Authorization", value = "Authorization token", required = true, dataType = "string", paramType = "header")})
    public ResultJson getUser(HttpServletRequest request){
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            return ResultJson.failure(ResultCode.UNAUTHORIZED);
        }
        UserDetail userDetail = authService.getUserByToken(token);
        return ResultJson.ok(userDetail);
    }

    @GetMapping("/users")
    @ApiOperation(value = "分页获取用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证令牌", required = true, dataType = "string", paramType = "header"),
            @ApiImplicitParam(name = "page", value = "页码，默认1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量，默认10", dataType = "int", paramType = "query")
    })
    public ResultJson<PageResult<UserDetail>> getAllUsers(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        String token = request.getHeader(tokenHeader);
        if (token == null) {
            return ResultJson.failure(ResultCode.UNAUTHORIZED);
        }

        PageResult<UserDetail> pageResult = authService.getAllUsersByPage(page, pageSize);
        return ResultJson.ok(pageResult);
    }
    @PostMapping(value = "/sign")
    @ApiOperation(value = "用户注册")
    public ResultJson sign(@RequestBody User user) {
        if (StringUtils.isAnyBlank(user.getName(), user.getPassword())) {
            return ResultJson.failure(ResultCode.BAD_REQUEST);
        }
        UserDetail userDetail = new UserDetail(user.getName(), user.getPassword(), Role.builder().id(1l).build());
        return ResultJson.ok(authService.register(userDetail));
    }

    @PostMapping(value = "/role")
    @ApiOperation(value = "创建角色")
    public ResultJson createRole(@RequestBody Role role) {
        authService.createRole(role);
        return ResultJson.ok();
    }

    @PutMapping(value = "/role")
    @ApiOperation(value = "修改角色信息")
    public ResultJson updateRole(@RequestBody Role role) {
        // 可以在这里添加对role.name长度的检查
        if (role.getName() != null && role.getName().length() >50) {
            return ResultJson.failure(ResultCode.BAD_REQUEST, "角色名称过长");
        }
        authService.updateRole(role);
        return ResultJson.ok();
    }

    @DeleteMapping(value = "/role/{roleId}")
    @ApiOperation(value = "删除角色")
    public ResultJson deleteRole(@PathVariable long roleId) {
        authService.deleteRole(roleId);
        return ResultJson.ok();
    }

    @GetMapping(value = "/roles")
    @ApiOperation(value = "分页获取角色列表")
    public ResultJson<PageResult<Role>> getAllRoles(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        PageResult<Role> roles = authService.getAllRoles(page, pageSize);
        return ResultJson.ok(roles);
    }


    @PostMapping(value = "/equipment")
    @ApiOperation(value = "创建装备")
    public ResultJson createEquipment(@RequestBody Equipment equipment) {
        authService.createEquipment(equipment);
        return ResultJson.ok();
    }

    @PostMapping(value = "/role/{roleId}/equipment/{equipmentId}")
    @ApiOperation(value = "添加装备到角色")
    public ResultJson addEquipmentToRole(@PathVariable long roleId, @PathVariable long equipmentId) {
        authService.addEquipmentToRole(roleId, equipmentId);
        return ResultJson.ok();
    }

    @DeleteMapping(value = "/role/{roleId}/equipment/{equipmentId}")
    @ApiOperation(value = "从角色移除装备")
    public ResultJson removeEquipmentFromRole(@PathVariable long roleId, @PathVariable long equipmentId) {
        authService.removeEquipmentFromRole(roleId, equipmentId);
        return ResultJson.ok();
    }

    @GetMapping(value = "/role/{roleId}/equipments")
    @ApiOperation(value = "获取角色的所有装备")
    public ResultJson<List<Equipment>> getRoleEquipments(@PathVariable long roleId) {
        List<Equipment> equipments = authService.getRoleEquipments(roleId);
        return ResultJson.ok(equipments);
    }

    @GetMapping(value = "/equipment/{equipmentId}")
    @ApiOperation(value = "根据ID获取装备")
    public ResultJson<Equipment> getEquipmentById(@PathVariable long equipmentId) {
        Equipment equipment = authService.getEquipmentById(equipmentId);
        return ResultJson.ok(equipment);
    }
    @GetMapping(value = "/equipments")
    @ApiOperation(value = "分页获取装备列表")
    public ResultJson<PageResult<Equipment>> getAllEquipments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        PageResult<Equipment> equipments = authService.getAllEquipments(page, pageSize);
        return ResultJson.ok(equipments);
    }

    @PutMapping(value = "/equipment")
    @ApiOperation(value = "更新装备信息")
    public ResultJson updateEquipment(@RequestBody Equipment equipment) {
        authService.updateEquipment(equipment);
        return ResultJson.ok();
    }



    @PostMapping(value = "/task")
    @ApiOperation(value = "创建任务")
    public ResultJson createTask(@RequestBody Task task) {
        authService.createTask(task);
        return ResultJson.ok();
    }

    @PostMapping(value = "/role/{roleId}/task/{taskId}")
    @ApiOperation(value = "为角色分配任务")
    public ResultJson assignTaskToRole(@PathVariable long roleId, @PathVariable long taskId) {
        authService.assignTaskToRole(roleId, taskId);
        return ResultJson.ok();
    }

    @PutMapping(value = "/role/{roleId}/task/{taskId}/complete")
    @ApiOperation(value = "标记角色的任务为已完成")
    public ResultJson markTaskAsCompleted(@PathVariable long roleId, @PathVariable long taskId) {
        authService.markTaskAsCompleted(roleId, taskId);
        return ResultJson.ok();
    }

    @GetMapping(value = "/role/{roleId}/tasks")
    @ApiOperation(value = "获取角色的所有任务")
    public ResultJson<List<Task>> getRoleTasks(@PathVariable long roleId) {
        List<Task> tasks = authService.getRoleTasks(roleId);
        return ResultJson.ok(tasks);
    }

    @GetMapping(value = "/role/{roleId}/tasks/incomplete")
    @ApiOperation(value = "获取角色未完成的任务")
    public ResultJson<List<Task>> getIncompleteRoleTasks(@PathVariable long roleId) {
        List<Task> tasks = authService.getIncompleteRoleTasks(roleId);
        return ResultJson.ok(tasks);
    }

    @GetMapping(value = "/role/{roleId}/tasks/completed")
    @ApiOperation(value = "获取角色已完成的任务")
    public ResultJson<List<Task>> getCompletedRoleTasks(@PathVariable long roleId) {
        List<Task> tasks = authService.getCompletedRoleTasks(roleId);
        return ResultJson.ok(tasks);
    }

    @GetMapping(value = "/task/{taskId}")
    @ApiOperation(value = "根据 ID 获取任务")
    public ResultJson<Task> getTaskById(@PathVariable long taskId) {
        Task task = authService.getTaskById(taskId);
        return ResultJson.ok(task);
    }

    @GetMapping(value = "/tasks")
    @ApiOperation(value = "分页获取所有任务")
    public ResultJson<PageResult<Task>> getAllTasks(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        PageResult<Task> tasks = authService.getAllTasks(page, pageSize);
        return ResultJson.ok(tasks);
    }

    @GetMapping("/tasks/incomplete")
    public List<Task> getIncompleteTasks(@RequestParam Long userId) {
        return authService.getIncompleteTasksByUserId(userId);
    }

    /**
     * 获取当前用户的已完成任务
     */
    @GetMapping("/tasks/completed")
    public List<Task> getCompletedTasks(@RequestParam Long userId) {
        return authService.getCompletedTasksByUserId(userId);
    }


    @PostMapping(value = "/player")
    @ApiOperation(value = "创建玩家信息")
    public ResultJson createPlayer(@RequestBody Player player) {
        authService.createPlayer(player);
        return ResultJson.ok();
    }

    @GetMapping(value = "/player/{playerId}")
    @ApiOperation(value = "根据 ID 获取玩家信息")
    public ResultJson<Player> getPlayerById(@PathVariable Long playerId) {
        Player player = authService.getPlayerById(playerId);
        return ResultJson.ok(player);
    }

    @GetMapping(value = "/player/account/{account}")
    @ApiOperation(value = "根据账号获取玩家信息")
    public ResultJson<Player> getPlayerByAccount(@PathVariable String account) {
        Player player = authService.getPlayerByAccount(account);
        return ResultJson.ok(player);
    }

    @PutMapping(value = "/player")
    @ApiOperation(value = "更新玩家信息")
    public ResultJson updatePlayer(@RequestBody Player player) {
        authService.updatePlayer(player);
        return ResultJson.ok();
    }

    @PostMapping(value = "/player/feedback")
    @ApiOperation(value = "创建玩家反馈")
    public ResultJson createPlayerFeedback(@RequestBody PlayerFeedback feedback) {
        authService.createPlayerFeedback(feedback);
        return ResultJson.ok();
    }

    @GetMapping(value = "/player/{playerId}/feedbacks")
    @ApiOperation(value = "获取玩家的反馈列表")
    public ResultJson<List<PlayerFeedback>> getPlayerFeedbacks(@PathVariable Long playerId) {
        List<PlayerFeedback> feedbacks = authService.getPlayerFeedbacks(playerId);
        return ResultJson.ok(feedbacks);
    }

    @GetMapping("/player/feedbacks/unprocessed")
    @ApiOperation("分页获取未处理的玩家反馈")
    public ResultJson<PageResult<PlayerFeedback>> getUnprocessedFeedbacks(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize
    ) {
        PageResult<PlayerFeedback> result = authService.getUnprocessedFeedbacks(page, pageSize);
        return ResultJson.ok(result);
    }

    @PutMapping(value = "/player/feedback/{feedbackId}/process")
    @ApiOperation(value = "标记玩家反馈为已处理")
    public ResultJson markFeedbackAsProcessed(@PathVariable Long feedbackId) {
        authService.markFeedbackAsProcessed(feedbackId);
        return ResultJson.ok();
    }


    @GetMapping(value = "/player/list")
    @ApiOperation(value = "分页获取玩家列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码，默认1", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量，默认10", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "搜索关键词", dataType = "string", paramType = "query")
    })
    public ResultJson<PageResult<Player>> getPlayerList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword
    ) {
        PageResult<Player> players = authService.getPlayerList(page, pageSize, keyword);
        return ResultJson.ok(players);
    }


    @DeleteMapping(value = "/player/{id}")
    @ApiOperation(value = "删除玩家")
    public ResultJson deletePlayer(@PathVariable Long id) {
        authService.deletePlayer(id);
        return ResultJson.ok();
    }
}
